package com.kye.express.business.customer_code.customer_code_manager;

import android.text.TextUtils;

import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.ErrorView;
import com.kye.express.contract.base.view.IView;
import com.kye.express.contract.base.view.LoadingView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.RetrofitManager;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.user.User;
import com.kye.model.bean.user.request.RequestCheckAuthorizedByUpdateCustomPassword;
import com.kye.model.bean.user.request.RequestGetUser;
import com.kye.model.bean.user.request.RequestUserUnBindCustomerCode;
import com.kye.model.service.UserService;

import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

public interface CustomerCodeManagerContract {

    interface CustomerCodeManagerView extends IView, LoadingView, ErrorView {

        void onUser(User user);

        void onSuccess();

        void onAuthorized(boolean authorized);

        void onCompanyName(String s);
    }

    class CustomerCodeManagerPresenter extends BasePresenter<CustomerCodeManagerView> {

        public void getUser() {
            UserSession.getInstance()
                    .getUserForRx()
                    .compose(getView().<User>bindToLifecycle())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            getView().onUser(user);
                        }
                    });
        }

        public void getCompanyName() {
            UserSession.getInstance()
                    .getUserForRx()
                    .firstOrError()
                    .map(new Function<User, String>() {
                        @Override
                        public String apply(User user) throws Exception {
                            String customCode = user.getCustomCode();
                            for (User.Address address : user.getLastAddress()) {
                                if (customCode.equals(address.getCompanyCode())) {
                                    return address.getCompanyName();
                                }
                            }
                            return null;
                        }
                    })
                    .subscribe(new Consumer<String>() {
                        @Override
                        public void accept(String s) throws Exception {
                            getView().onCompanyName(s);
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {

                        }
                    });
        }

        public void unbindCustomerCode(final String phone, String customCode) {
            RetrofitManager.getInstance()
                    .createOpenApiService(UserService.class)
                    .unbindCustomerCode(new RequestUserUnBindCustomerCode(phone, customCode))
                    .compose(getView().<OpenApiResult<User>>bindToLifecycleDestroy())
                    .doOnSuccess(new Consumer<OpenApiResult<User>>() {
                        @Override
                        public void accept(OpenApiResult<User> userOpenApiResult) throws Exception {
                            User user = userOpenApiResult.getData();
                            if (user == null) return;
                            UserSession.getInstance().setUser(user);
                        }
                    })
                    .onErrorResumeNext(new Function<Throwable, SingleSource<? extends OpenApiResult<User>>>() {
                        @Override
                        public SingleSource<? extends OpenApiResult<User>> apply(Throwable throwable) throws Exception {
                            return RetrofitManager.getInstance().createOpenApiService(UserService.class).getUser(new RequestGetUser(phone));
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<User>() {
                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<User> result, User user) {
                            if (!TextUtils.isEmpty(user.getCustomCode())) {
                                getView().onError();
                                return;
                            }

                            getView().onSuccess();
                        }

                        @Override
                        public void onApiError(OpenApiResult<User> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        public void checkAuthorizedByUpdateCustomPassword() {
            UserSession.getInstance()
                    .getUserForRx()
                    .firstOrError()
                    .flatMap(new Function<User, SingleSource<OpenApiResult<Object>>>() {
                        @Override
                        public SingleSource<OpenApiResult<Object>> apply(User user) throws Exception {
                            return RetrofitManager.getInstance()
                                    .createOpenApiService(UserService.class)
                                    .checkAuthorizedByUpdateCustomPassword(new RequestCheckAuthorizedByUpdateCustomPassword(user.getPhone(), user.getCustomCode()));
                        }
                    })
                    .compose(getView().<OpenApiResult<Object>>bindToLifecycleDestroy())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<Object>() {
                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError();
                        }

                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<Object> result, Object o) {
                            getView().onAuthorized(true);
                        }

                        @Override
                        public void onApiError(OpenApiResult<Object> result, int code, String msg) {
                            getView().onAuthorized(false);
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }
    }
}
